package com.junjie.blibli.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.junjie.blibli.Constant.RocketMqConstant;
import com.junjie.blibli.Entity.UserMoment;
import com.junjie.blibli.dao.UserMomentDao;
import com.junjie.blibli.service.UserMomentService;
import com.junjie.blibli.util.RocketMQUtil;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@Service
public class UserMomentServiceImpl implements UserMomentService {
    @Autowired
    private UserMomentDao userMomentDao;

    //注入整个spring的上下文，通过这个上下文可以获取到任意bean以及其他内容
    //之所以引入这个，是为了获取生产者和消费者
    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public void addUserMoments(UserMoment userMoment) throws Exception {
        userMoment.setCreateTime(new Date());
        userMomentDao.addUserMoments(userMoment);
        //通过上下文获取生产者
        DefaultMQProducer producer = (DefaultMQProducer) applicationContext.getBean("momentsProducer");
        //创建message对象，第一个参数是指定属于哪个主题，第二个参数是消息
        // 注意要将对象转换成json字符串，再变成byte数组
        Message message = new Message(RocketMqConstant.TOPIC_MOMENTS
                , JSONObject.toJSONString(userMoment).getBytes(StandardCharsets.UTF_8));
        RocketMQUtil.syncSendMsg(producer,message);
    }

    @Override
    public List<UserMoment> getUserSubscribedMoments(Long userId) {
        String key = "subscribed-"+userId;
        String listStr = redisTemplate.opsForValue().get(key);
        return JSONObject.parseArray(listStr,UserMoment.class);
    }
}
